package com.byzk.p2p.app.controller;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.byzk.p2p.admin.base.controller.BaseController;
import com.byzk.p2p.admin.base.util.Constant;
import com.byzk.p2p.admin.base.util.DateUtils;
import com.byzk.p2p.admin.base.util.JsonMsg;
import com.byzk.p2p.admin.base.util.PageInfo;
import com.byzk.p2p.admin.borrow.dto.Borrow;
import com.byzk.p2p.admin.borrow.dto.BorrowApply;
import com.byzk.p2p.admin.borrow.dto.Change;
import com.byzk.p2p.admin.borrow.service.BorrowService;
import com.byzk.p2p.admin.borrow.service.ChangeService;
import com.byzk.p2p.admin.borrow.service.TenderService;
import com.byzk.p2p.admin.borrow.vo.BorrowTenderVo;
import com.byzk.p2p.admin.borrow.vo.BorrowVo;
import com.byzk.p2p.admin.borrow.vo.ChangeVo;
import com.byzk.p2p.admin.borrow.vo.MyChangeVo;
import com.byzk.p2p.admin.borrow.vo.UserTenderVo;
import com.byzk.p2p.admin.money.service.BorrowPaymentDetailService;
import com.byzk.p2p.admin.money.vo.BorrowPaymentDetailVo;
import com.byzk.p2p.admin.system.service.ResourceService;
import com.byzk.p2p.admin.system.vo.ResourceVo;
import com.byzk.p2p.admin.user.dto.User;
import com.byzk.p2p.admin.user.dto.UserAccount;
import com.byzk.p2p.admin.user.service.UserAccountService;
import com.byzk.p2p.admin.user.service.UserService;

/**
 * app端投标操作
 * 
 * @author suker.zhou
 */
@Controller
@RequestMapping("/app")
@Scope("prototype")
public class AppBorrowController extends BaseController {

	@Autowired
	private BorrowService borrowService;
	
	@Autowired
	private ChangeService changeService;
	
	@Autowired
	private TenderService tenderService;
	
	@Autowired
	private ResourceService resourceService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private UserAccountService accountService;
	
	@Autowired
	private BorrowPaymentDetailService borrowPaymentDetailService ; 

	/**
	 * 查询所有借款标(除了新手标)
	 * 
	 * @param info
	 * @throws Exception
	 */
	@RequestMapping(value = "/borrow/list")
	public void borrowList(@ModelAttribute BorrowVo info) throws Exception {
		info.setTimingShow(new Date());
		super.printJSON(new JsonMsg(-1, "理财列表查询成功！", borrowService.borrowList(info)));
		return;
	}
	
	/**
	 * 借款标详情
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/borrow/detail")
	public String borrowDetail(@RequestParam Integer id) throws Exception {
		BorrowVo borrowVo=borrowService.detailBorrowVo(id);
		if(borrowVo == null){
			super.printJSON(new JsonMsg(1, "详情获取失败 ", borrowVo));
			return null;
		}
		
		/** 计算预约倒计时 **/
		if(borrowVo.getTimingShow() != null){
			int second = (int) ((borrowVo.getTimingShow().getTime()-new Date().getTime())/1000L);
			if(second > 0 && second < (60*60*2)) {//两小时以内
				borrowVo.setCountDown(DateUtils.formatSecond(second));
			}
		}
		super.printJSON(new JsonMsg(-1, "详情获取成功", borrowVo));
		return null;
	}
	
	/**
	 * 投资标用户投资记录
	 * @param userTender
	 * @return
	 */
	@RequestMapping("/borrow/tender/record")
	public String listTenderRecord(@ModelAttribute UserTenderVo userTender){
		try {
			userTender.setUserId(Integer.parseInt(userTender.getUid()));
			PageInfo<BorrowTenderVo> pageInfo = tenderService.getUserTender(userTender);
			super.printJSON(new JsonMsg(-1, "操作成功", pageInfo));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 投资标资质图片
	 * @param id
	 * @return
	 */
	@RequestMapping("/borrow/detail/aptitude")
	public String aptitude(@RequestParam Integer id){
		try {
			Borrow borrow=borrowService.detailBorrow(id);
			List<ResourceVo> listResource= null ; 
			String ids = borrow.getPersonalInfo() +","+ borrow.getCapitalInfo() ; 
			if(org.apache.commons.lang.StringUtils.isNotBlank(ids) ){
				listResource=resourceService.getResourcesById(ids);			
			}
			if(listResource != null && listResource.size()>0){
				super.printJSON(new JsonMsg(-1, "操作成功", listResource));
			}else{
				super.printJSON(new JsonMsg(-1, "获取失败"));
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 新手标
	 * @return
	 */
	@RequestMapping(value="/borrow/new")
	public String newBorrow() throws Exception {
		BorrowVo info=new BorrowVo();
		info.setStatus("new");
		List<Borrow> borrowList=borrowService.listLastNewBorrow();
		if(borrowList.size()>0){
			super.printJSON(new JsonMsg(-1, "新手标获取成功！", borrowList.get(0)));
		}else{
			super.printJSON(new JsonMsg(0, "暂无新手标！", null));
		}
		return null;
	}
	
	/**
	 * 新增债券转让
	 * @param info
	 * @throws Exception
	 */
	@RequestMapping(value = "/change/save")
	public void saveChange(@ModelAttribute Change info) throws Exception {
		Integer uid = Constant.strToInt(info.getUid());
		if (uid == -1) {
			super.printJSON(new JsonMsg(1, "请先登录！"));
			return;
		}
		info.setUid(info.getUid());
		changeService.saveOrUpdateChange(info);
		super.printJSON(new JsonMsg(-1, "操作成功！"));
		return;
	}
	
	/**
	 * 债券转让列表
	 * @param info
	 * @throws Exception
	 */
	@RequestMapping(value = "/change/list")
	public void listChange(@ModelAttribute ChangeVo info) throws Exception{
		super.printJSON(new JsonMsg(-1, "债券转让列表查询成功！", changeService.listChange(info.getIndex(), info.getLimit(),info)));
		return;
	}
	
	/**
	 * 查询一条债券转让
	 * @param changeId
	 * @throws Exception
	 */
	@RequestMapping(value = "/change/detail")
	public void changeDetail(@RequestParam("id") Integer id) throws Exception{
		super.printJSON(new JsonMsg(-1, "债券转让详情查询成功！", changeService.getChange(id)));
		return;
	}
	
	/**
	 * 债权购买记录
	 * @param id
	 * @throws Exception
	 */
	@RequestMapping(value = "/change/buy/list")
	public void changeBuyList(@RequestParam("id") Integer id) throws Exception{
		super.printJSON(new JsonMsg(-1, "债券转让购买查询成功！", changeService.listByChangeId(id)));
		return;
	}
	
	/**
	 * 竞拍
	 * @param info
	 * @throws Exception
	 */
	@RequestMapping(value = "/change/buy")
	public void saveOrUpdateRecord(@RequestParam("uid") Integer uid,
								   @RequestParam("changeId") Integer changeId) throws Exception {
		if (uid == null) {
			printJSON(new JsonMsg(1, "请先登录！", null));
			return;
		}
		User frontUser=userService.getById(uid);
		if (frontUser == null) {
			printJSON(new JsonMsg(1, "数据异常,请重新登录！", null));
			return;
		}		
		
		ChangeVo changeVo = changeService.getChange(changeId);
		if (changeVo == null) {
			printJSON(new JsonMsg(1, "购买失败！"));
			return;
		}
		if(!"T".equals(changeVo.getStatus())){
			printJSON(new JsonMsg(1, "状态异常，不能进行转让"));
			return;			
		}		
		if("Y".equals(changeVo.getStatus())){
			printJSON(new JsonMsg(1, "转让已完成！"));
			return;			
		}

		UserAccount account=accountService.getByUserId(uid);
		
		if(account.getBalance()<changeVo.getMin()){
			printJSON(new JsonMsg(1, "可用余额不足,请充值！"));
			return;				
		}
		if(changeVo.getUserId().equals(frontUser.getId())){
			printJSON(new JsonMsg(1, "自己发布的债权自己不能购买！"));
			return;				
		}
		Borrow borrow=borrowService.detailBorrow(changeVo.getBorrowId());
		BorrowApply apply=borrowService.getBorrowApply(borrow.getBorrowApplyId());
		if(apply.getUserId().equals(frontUser.getId())){
			printJSON(new JsonMsg(1, "自己不能回购自己借款的标！"));
			return;				
		}
		if (DateUtils.getDistanceTimeNum(new Date(), changeVo.getOverdue())>=0) {
			printJSON(new JsonMsg(1, "已超过到期时间，转让失败！"));
			return;
		}
		
		printJSON(new JsonMsg(-1, "购买成功！"));
		
	}
	
	@RequestMapping(value = "/borrow/buy")
	public String borrowBuy(@RequestParam("uid") Integer uid,
								   @RequestParam("borrowId") Integer borrowId) throws Exception {
		UserAccount account =  accountService.getByUserId(uid);
		Borrow borrow = borrowService.getBorrowById(borrowId);
		BorrowVo borrowVo = new BorrowVo() ; 
		borrowVo.setNotTenderMoney(borrow.getNotTenderMoney());
		borrowVo.setBalance(account.getBalance());
		super.printJSON(new JsonMsg(-1, "详情获取成功", borrowVo));
		return null ; 
	} 
	
	
	/**
	 * 债权购买记录
	 * @param uid    用户id号
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/myChange/buy")
	public String changebuyList(@ModelAttribute MyChangeVo vo) throws Exception {
		
		PageInfo<MyChangeVo> changeList = changeService.getChangeListByUserId(vo);
		super.printJSON(new JsonMsg(-1, "获取成功", changeList));
		
		return null ;
	}
	
	/**
	 * 还款记录表
	 * @param vo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/repayment/list")
	public String repaymentList(BorrowPaymentDetailVo vo) throws Exception {
		super.printJSON(new JsonMsg(-1, "获取成功", borrowPaymentDetailService.repaymentList(vo)));
		
		return null ;
	}
}
